window.baseURL = document.URL.replace(/#.*$/, '');

// TODO watch for documentElement replacement
(function() {

var messages = extension.messages;

function checkStorage() {
    chrome.storage.local.get(window.baseURL, function(obj) {
        if (window.baseURL in obj)
            messages.runtime.send('add-components');
    });
}

function onChanged(changeInfo, area) {
    if (area === 'local') {
        if (window.Webtags !== API)
            chrome.storage.onChanged.removeListener(onChanged);
        else if (window.baseURL in changeInfo)
            messages.runtime.send('add-components');
    }
}

function methodWrapper(name) {
    return function(arg) {
        messages.runtime.send('add-components');
        messages.listen({
            'extension-ready': function() {
                messages.ignore(this);
                window.Webtags[name](arg);
            }
        });
    }
}

var API = {
    showDialog: methodWrapper('showDialog'),
    saveTag: methodWrapper('saveTag'),
    clearTags: methodWrapper('clearTags'),
    toggleTags: methodWrapper('toggleTags'),
    showHighlighter: methodWrapper('showHighlighter')
};

if (window.Webtags == null) {
    window.Webtags = API;
    checkStorage();
    chrome.storage.onChanged.addListener(onChanged);
}

})();
